package com.qf.common.rocket.utils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qf.common.rocket.entity.MsgRetry;
import com.qf.common.rocket.mapper.MsgRetryMapper;
import com.qf.common.rocket.param.PointMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @author zdl
 * @date 2025/4/16
 */
@Component
@Slf4j
public class RocketMQUtils {
    @Resource
    private RocketMQTemplate rocketMQTemplate;
    @Resource
    private MsgRetryMapper msgRetryMapper;

    /**
     * 发送同步消息
     *
     * @param msg
     */
    public void sendSyncMsg(String msg) {
        String keys = UUID.randomUUID().toString();
        //添加数据
        MsgRetry msgRetry = new MsgRetry();
        msgRetry.setMsg(msg);
        msgRetry.setTag("");
        msgRetry.setTopic("USER_TOPIC1");
        msgRetry.setKeys(keys);
        msgRetryMapper.insert(msgRetry);
        Message<String> message = MessageBuilder.withPayload(msg)
                // 设置消息的key，用于标识消息的唯一性，可用于消息去重
                .setHeader(RocketMQHeaders.KEYS, keys)
                .build();
        try {
            rocketMQTemplate.syncSend("USER_TOPIC1", message);
//            msgRetryMapper.delete(new LambdaQueryWrapper<>(MsgRetry.class)
//                    .eq(MsgRetry::getKeys, keys));
        } catch (Exception e) {
            //throw new RuntimeException(e);
            // 正常在这里添加数据
            //msgRetryMapper.insert(new MsgRetry(msg));
        }
    }

//    public void sendPoint(PointMessage pointMessage) {
//        rocketMQTemplate.convertAndSend("point-topic", pointMessage);
//    }
//
//    public void sendCloseOrder(String orderNo) {
//        // 发送延迟消息
//        log.info("延迟发送消息 msg:{}", orderNo);
//        // rocketmq 5.0 之后版本 可以任意指定延迟时间
//        // 延迟时间 单位：毫秒
//        rocketMQTemplate.syncSendDelayTimeSeconds("close-topic", orderNo, 30 * 60);
//    }

    public void sendDelayMsg(String topic, String tag, String msg, long delayTime) {
        if (!StringUtils.hasLength(tag)){
            rocketMQTemplate.syncSendDelayTimeSeconds(topic , msg, delayTime);
        }else {
            rocketMQTemplate.syncSendDelayTimeSeconds(topic + ":" + tag, msg, delayTime);
        }
    }
}
